/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helpdesk;

import javax.servlet.http.HttpSessionBindingListener;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;

/**
 * Check if a user is logged in
 *
 * You must add a loginListener to the session of the user for this to work.
 * When the user logs out, you should remove the value from the user's session.
 *
 * When a session times out, the user will be logged out.
 *
 * If the user does not log out, they will be 'logged in' until their his/her
 * session expires.
 *
 * @author brian
 */
public class LoginCheck {
    static Map<Integer, Boolean> users = null;

    /**
     * Check if a user is logged in.
     *
     * @param userId
     * @return
     */
    public static boolean isLoggedIn(int userId)
    {
        if (users == null)
            createUsers();

        if (users.containsKey(userId))
        {
            return true;
        }

        return false;
    }

    /**
     * Used to create the HashMap that stores the status of the users the first
     * time this class is used.
     */
    private static synchronized void createUsers()
    {
        if (users == null)
        {
            users = Collections.synchronizedMap(new HashMap<Integer, Boolean>());
        }
    }

    /**
     * Must be bound to the user's session for this to work properly.
     */
    public static HttpSessionBindingListener getListener(int userId)
    {
        HttpSessionBindingListener listener;
        listener = new LoginListener(userId);
                
        return listener;
    }

    /**
     * When this class is bound/unbound from a session, valueBound/valueUnbound
     * is invoked.
     */
    private static class LoginListener implements HttpSessionBindingListener
    {
        int userId;

        public LoginListener(int userId)
        {
            this.userId = userId;
        }

        public void valueBound(javax.servlet.http.HttpSessionBindingEvent ev)
        {
            if (users == null)
                createUsers();
            users.put(userId, Boolean.TRUE);
        }

        public void valueUnbound(javax.servlet.http.HttpSessionBindingEvent ev)
        {
            if (users == null)
                createUsers();
            users.remove(userId);
        }
    }
}
